package cn.scxy.bookcity.service.impl;

import cn.scxy.bookcity.ex.ServiceException;
import cn.scxy.bookcity.mapper.ShoppingCarMapper;
import cn.scxy.bookcity.pojo.dto.ShoppingCarAddNewDTO;
import cn.scxy.bookcity.pojo.entity.CarProduct;
import cn.scxy.bookcity.pojo.vo.ShoppingCarStandardVO;
import cn.scxy.bookcity.pojo.vo.shoppingCarVO;
import cn.scxy.bookcity.service.IShoppingCarService;
import cn.scxy.bookcity.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ShoppingCarServiceImpl implements IShoppingCarService {
    @Autowired
    private ShoppingCarMapper mapper;

    public ShoppingCarServiceImpl() {
    }

    @Override
    public List<shoppingCarVO> list(Long uid) {
        return mapper.list(uid);
    }

    @Override
    public void insert(ShoppingCarAddNewDTO shoppingCarAddNewDTO) {
        log.debug("开始处理【添加购物车商品】的业务，参数：{}", shoppingCarAddNewDTO);

        CarProduct carProduct = new CarProduct();
        BeanUtils.copyProperties(shoppingCarAddNewDTO, carProduct);
        carProduct.setNum(shoppingCarAddNewDTO.getSnum());
        log.debug("即将插入购物车数据：{}", carProduct);
        int rows = mapper.insert(carProduct);
        if (rows != 1) {
            String message = "添加购物车失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("插入购物车数据完成");
    }


    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据id删除购物车商品】的业务，参数：{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        ShoppingCarStandardVO queryResult = mapper.getStandardById(id);
        if (queryResult == null) {
            // 是：无此id对应的数据，将不允许执行删除操作，则抛出异常
            String message = "删除购物车商品失败，尝试访问的数据不存在！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", id);
        int rows = mapper.deleteById(id);
        if (rows != 1) {
            String message = "删除购物车商品失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void deleteByIds(Long[] ids) {
        // 调用Mapper对象的deleteById()方法执行删除
        log.debug("即将执行删除，参数：{}", ids);
        int rows = mapper.deleteByIds(ids);
        if (rows != 1) {
            String message = "删除购物车商品失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }
}
